#include "tcp.h"
#include "head.h"

/* Useage:初始化连接  */
int getParameter(char *key, char *value){

    FILE * file = fopen("config.ini", "r");
    while(1){
        char line[100];
        bzero(line, sizeof(line));
        // 读一行数据
        char *res = fgets(line, sizeof(line), file);
        if(res == NULL){
            char buf[] = "没有要找的内容 \n";
            memcpy(value, buf, strlen(buf));
            return -1;
        }
        // 处理数据
        char *line_key = strtok(line, "=");
        if(strcmp(key, line_key) == 0){
        // 要找的内容
        char *line_value = strtok(NULL, "=");
        memcpy(value, line_value, strlen(line_value));
        return 0;
        }
    }
    return 0;
}

int tcpInit(){
    char ip[100] = {0};
    char port[100] = {0};

    getParameter("ip", ip);
    getParameter("port", port);

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);    

    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);
    
    int ret = connect(socket_fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
    printf("Connecting to server...\n");
    ERROR_CHECK(ret, -1, "connect");

    return socket_fd;
}

int epollAddReadEvent(int epoll_fd, int fd){
    
    struct epoll_event event;
    event.data.fd = fd;
    event.events = EPOLLIN;
    int ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event);
    printf("Epollin is adding...\n");
    ERROR_CHECK(ret, -1, "epoll_ctl");

    return 0;
}
